package com.fingersoft.feature.login;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.fingersoft.business.BusinessContext;
import com.fingersoft.business.location.LocationCallback;
import com.fingersoft.business.location.LocationData;
import com.fingersoft.common.ICallback;
import com.fingersoft.common.preference.UserAppPreferenceHelper;
import com.fingersoft.common.preference.provider.UserIdProvider;
import com.fingersoft.config.ConfigFeature;
import com.fingersoft.feature.login.api.LoginData;
import com.fingersoft.feature.personal.ui.EnterpriseConfigurationActivity;
import com.fingersoft.feature.personal.ui.FindBackPasswordActivity;
import com.fingersoft.feature.personal.ui.SecondCheckActivity;
import com.fingersoft.feature.webview.WebViewManager;
import com.fingersoft.im.BuildConfig;
import com.fingersoft.im.api.UserAgent;
import com.fingersoft.im.api.base.AbsCallbackWithDeviceCheck;
import com.fingersoft.im.api.base.BaseModelCallback2;
import com.fingersoft.im.api.base.BaseResponse2;
import com.fingersoft.im.event.EventManager;
import com.fingersoft.im.utils.AppConfigUtils;
import com.fingersoft.im.utils.AppUtils;
import com.fingersoft.im.utils.EnvironmentUtils;
import com.fingersoft.im.utils.JSONUtils;
import com.fingersoft.theme.ThemeM;
import com.fingersoft.util.DeviceHelper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.BaseRequest;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;


/**
 * @deprecated use SealLoginContext2.kt
 */
@Deprecated
public abstract class SealLoginContext implements ILoginContext {

    protected final Application application;

    @Deprecated
    public SealLoginContext(Application application) {
        this.application = application;
    }

    @Override
    public void onModuleStart(Context context) {
    }

    @Override
    public UserAppPreferenceHelper getUserAppPreferenceHelper() {
        return new UserAppPreferenceHelper(new UserIdProvider() {
            @NotNull
            @Override
            public String getUserId() {
                return AppUtils.getUser().getUserId();
            }
        });
    }

    @Override
    public String getCurrentUserId() {
        return AppUtils.getUser().getUserId();
    }

    @Override
    public String getCurrentUserName() {
        return AppUtils.getUser().getUserName();
    }

    @Override
    public String getCurrentUserPassword() {
        return AppUtils.getUser().getPassword();
    }

    @Override
    public String getMobile(){
        return AppUtils.getUser().getMobile();
    }

    @Override
    public void onLogin(Activity activity, LoginData loginResponse, ILoginCallback iLoginCallback) {

        getUserAppPreferenceHelper().putBoolean("isJustLogout", false);
        EventBus.getDefault().post(new EventManager.OnLoginSucceed());
        iLoginCallback.onSuccess();
    }

    @Override
    public void onSecondCheck(Activity loginActivity, LoginData data, ISecondCheckCallback iSecondCheckCallback) {
        if (data.getUser().getMobile() == null || data.getUser().getMobile().trim().isEmpty()) {
            Toast.makeText(loginActivity.getBaseContext(), "本账户没有设置手机号", Toast.LENGTH_SHORT).show();
            iSecondCheckCallback.onError();
            return;
        }
        SecondCheckActivity.Companion.startChangePasswordActivity(loginActivity, data.getUser().getMobile(), new com.fingersoft.feature.personal.callback.ISecondCheckCallback() {
            @Override
            public void onSuccess() {
                iSecondCheckCallback.onSuccess();
            }

            @Override
            public void onError() {
                iSecondCheckCallback.onError();
            }
        });
    }

    @Override
    public void setThemeStyle(View view) {
        ThemeM.setThemeStyle(view);
    }

    @Override
    public boolean has_start() {
        return AppUtils.isHas_start();
    }
    @Override
    public void setHas_start() {
         AppUtils.setHas_start();
    }

    @Override
    public boolean loginAppNameIsCustomImg() {
        return AppUtils.loginAppNameIsCustomImg();
    }

    /**
     * 获取初始化配置
     */
    public void initBasicAppInfo(Activity activity) {


    }

    @Override
    public String getDid() {
        return AppUtils.getTokenInfo().getDid();
    }

    @Override
    public String getCurrentUserToken() {
        return AppUtils.getTokenInfo().getUserToken();
    }

    @Override
    public String getApiUrl(String path) {
        return AppUtils.getApiUrl(path, null);
    }

    @Override
    public String getECODE() {
        return AppUtils.J_ECODE;
    }

    @Override
    public String getOLDCODE() {//此处就是需要读取原始配置
        return BuildConfig.J_ECODE.trim();
    }

//                @Override
//                public void saveCurrentUser(String userName, String password, String did, LoginResponse.LoginData data) {
//                    AppUtils.saveCurrentUserInfo(data.getUserInfo());
//
//                    final WorkUser user = new WorkUser();
//                    user.setUserId(data.getUserInfo().getId());
//                    user.setUserName(userName);
//                    user.setRealName(data.getUserInfo().getName());
//                    user.setPassword(password);
//                    user.setEmpLivingPhoto(data.getUserInfo().getUserIcon());
//                    user.setImid(data.getUserInfo().getImid());
//                    AppUtils.saveUser(user);
//
//
//                    TokenInfo tokenInfo = AppUtils.getTokenInfo();
//                    // tokenInfo.setAppPath(data.getAppPath());
//                    tokenInfo.setDid(did);
//                    tokenInfo.setUid(user.getUserId());
//                    tokenInfo.setUserToken(!TextUtils.isEmpty(data.getUserToken()) ? data.getUserToken() : data.getUserInfo().getUsertoken());
//                    AppUtils.saveTokenInfo(tokenInfo);
//                }

    @Override
    public boolean isLogin() {
        return AppUtils.isLogged();
    }

    @Override
    public boolean isUseTheme() {
        return AppUtils.useTheme();
    }

    @Override
    public boolean loginBackgroundIsFull() {
        return AppUtils.loginBackgroundIsFull();
    }

    @Override
    public boolean loginFontStyleIsDark() {
        return AppUtils.loginFontStyleIsDark();
    }

    @Override
    public String loginButtonColor() {
        return AppUtils.loginButtonColor();
    }

    @Override
    public String getCurrentUserIcon() {
        return AppUtils.getUser().getEmpLivingPhoto();
    }


    @Override
    public void sendCode(String path, String json, ICallback callback) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
            .upJson(json)
            .execute(new BaseModelCallback2<BaseResponse2>(BaseResponse2.class) {
                @Override
                public void onSuccess(BaseResponse2 loginResponse2, Call call, Response response) {
                    super.onSuccess(loginResponse2, call, response);
                    if (AppUtils.showApiSucceedErrorToast(loginResponse2)) {
                        callback.onError();
                        return;
                    }
                    callback.onSuccess(loginResponse2.getData());
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    AppUtils.showApiErrorToast();
                    callback.onError();
                }

                @Override
                public void onBefore(BaseRequest request) {
                    super.onBefore(request);
                }

                @Override
                public void onAfter(BaseResponse2 loginResponse2, Exception e) {
                    super.onAfter(loginResponse2, e);
                }

            });

    }
    @Override
    public void postString(String path, String json, ICallback<BaseResponse2<String>> callback) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
            .upJson(json)
            .execute(new BaseModelCallback2<BaseResponse2<String>>(BaseResponse2.class) {
                @Override
                public void onSuccess(BaseResponse2<String> loginResponse2, Call call, Response response) {
                    super.onSuccess(loginResponse2, call, response);
                    if (path.contains("a·e")) {
                        if (null == loginResponse2 || 403 == loginResponse2.getCode() || null == loginResponse2.getData()) {
                            callback.onError(null == loginResponse2 ? null : loginResponse2.getMsg());
                            return;
                        }
                    }
                    if (AppUtils.showApiSucceedErrorToast(loginResponse2)) {
                        callback.onError();
                        return;
                    }
                    callback.onSuccess(loginResponse2);
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    AppUtils.showApiErrorToast();
                    callback.onError();
                }

                @Override
                public void onBefore(BaseRequest request) {
                    super.onBefore(request);
                }

                @Override
                public void onAfter(BaseResponse2<String> loginResponse2, Exception e) {
                    super.onAfter(loginResponse2, e);
                }

            });

    }

    @Override
    public String getDeviceId() {
        return DeviceHelper.getDeviceID(application);
    }

    @Override
    public String getLoginSubTitle() {
        return AppUtils.loginSubTitle();
    }

    @Override
    public int getLoginTextColor() {
        return Color.parseColor(AppUtils.loginButtonTextColor());
    }

    @Override
    public int getThemeColor() {
        return ThemeM.getThemeColor();
    }

    @Override
    public void onPreLogin(Activity activity) {
        registerDevice(activity, new ICallback<ConfigFeature.ConfigData>(ConfigFeature.ConfigData.class) {
            @Override
            public void onSuccess(ConfigFeature.ConfigData data) {
                SharedPreferences sp1 = activity.getSharedPreferences("app_info", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp1.edit();
                editor.putBoolean("isFirstLaunch", false);
                editor.commit();

            }
        });
    }


    public class LoginResponse2 extends BaseResponse2<LoginData> {

    }

    @Override
    public abstract void gotoMainActivity(Activity loginActivity);

    @Override
    public void getLocation(Activity loginActivity, LocationCallback callback) {
        if(BusinessContext.Companion.getMLocationProvider()!=null) {
            BusinessContext.Companion.getMLocationProvider().getLocation(loginActivity, callback);
        }
    }

    @Override
    public void releaseLocationRef() {
        if (BusinessContext.Companion.getMLocationProvider() != null) {
            BusinessContext.Companion.getMLocationProvider().release();
        }
    }

    @Override
    public void gotoFindBackPasswordActivity(Activity loginActivity) {
        FindBackPasswordActivity.Companion.startForgetPasswordActivity(loginActivity);
    }

    @Override
    public void gotoFindBackPasswordH5(Activity loginActivity, String fpUrl, String title) {
        WebViewManager.Companion.openWebView(loginActivity, fpUrl, title);
    }

    @Override
    public void gotoEnterpriseConfiguration(Activity loginActivity) {
        EnterpriseConfigurationActivity.start(loginActivity);
    }

    private void registerDevice(Context context, ICallback callback) {
        registerDevice(context, null, callback);
    }

    public static void registerDevice(Context context, @Nullable HashMap<String, String> extra, @NonNull ICallback callback) {
        Log.i("SealLoginContext", "registerDevice");
        JSONObject params = new JSONObject();
        try {
            params.put("deviceId", DeviceHelper.getDeviceID(context));
            params.put("productName",EnvironmentUtils.Companion.getBrand()+' '+ EnvironmentUtils.Companion.getModelName());//手机型号,如"HUAWEI P20"
            params.put("modelName", EnvironmentUtils.Companion.getDeviceName());//设备名称,如"小米6"
            params.put("osName", EnvironmentUtils.Companion.getOSName());
            params.put("osVersion", EnvironmentUtils.Companion.getOSVersion());
            params.put("imeiAndMeid", EnvironmentUtils.Companion.getImeiAndMeid(context));
            params.put("pixels", EnvironmentUtils.Companion.getDisplayMetrics(context));//获取手机分辨率
            if (extra != null) {
                for (Map.Entry<String, String> ex : extra.entrySet()) {
                    params.put(ex.getKey(), ex.getValue());
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.post(AppUtils.getApiUrl("am/device/register", AppUtils.J_ECODE))
                .headers("Emp-Info", JSONUtils.toJsonString(new UserAgent(AppUtils.getTokenInfo().getUserToken(), AppUtils.getTokenInfo().getDid())))
                .upJson(params.toString())
                .execute(new BaseModelCallback2<BaseResponse2>(BaseResponse2.class) {
                    @Override
                    public void onSuccess(BaseResponse2 baseResponse2, Call call, Response response) {
                        super.onSuccess(baseResponse2, call, response);
                        callback.onSuccess(baseResponse2.getData());
//                        registerDefultRuls(callback);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        callback.onError();
                    }

                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onAfter(BaseResponse2 baseResponse2, Exception e) {
                        super.onAfter(baseResponse2, e);
                    }
                });
    }

    @Override
    public void uploadLocation(Context context, LocationData locationData, String locationUid) {
        JSONObject params = new JSONObject();
        try {
            params.put("location_uuid", locationUid);
            params.put("longitude", locationData.getLongitude());
            params.put("latitude", locationData.getLatitude());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.post(AppUtils.getApiUrl("i/user/setLoginLocation", AppUtils.J_ECODE))
                .headers("Emp-Info", JSONUtils.toJsonString(new UserAgent(AppUtils.getTokenInfo().getUserToken(), AppUtils.getTokenInfo().getDid())))
                .upJson(params.toString())
                .execute(new BaseModelCallback2<BaseResponse2>(BaseResponse2.class) {
                    @Override
                    public void onSuccess(BaseResponse2 baseResponse2, Call call, Response response) {
                        super.onSuccess(baseResponse2, call, response);
                        Log.d("location",response.toString());
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }

                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onAfter(BaseResponse2 baseResponse2, Exception e) {
                        super.onAfter(baseResponse2, e);
                    }
                });
    }

    @Override
    public Object getConfig(Context context) {
        return AppConfigUtils.getAppConfigInfo(context);
    }
}
